package com.example.zhilongzhang.constructionpayapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.zhilongzhang.constructionpayapp.R;
import com.example.zhilongzhang.constructionpayapp.base.App;
import com.example.zhilongzhang.constructionpayapp.base.BaseActivity;
import com.example.zhilongzhang.constructionpayapp.base.ToastManager;
import com.example.zhilongzhang.constructionpayapp.bean.CustomerBean;
import com.example.zhilongzhang.constructionpayapp.bean.QrCodeBean;
import com.example.zhilongzhang.constructionpayapp.bean.UserInfoBean;
import com.example.zhilongzhang.constructionpayapp.dialog.WaitDialog;
import com.example.zhilongzhang.constructionpayapp.http.HttpMethod;
import com.example.zhilongzhang.constructionpayapp.method.bluetooth.ToothMethod;
import com.example.zhilongzhang.constructionpayapp.util.SpUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class SearchActivity extends BaseActivity {
    ImageView ivCancelNumber;
    EditText edNumber;
    WaitDialog mDialog;
    TextView tvMoney, tvAddress, tvName, tvInfo, tvType;
    String strMoney = "0";
    LinearLayout linCust;
    String strNumber = "", strYear = "", strType = "", strName = "", strAddress = "";
    // 用户编号;年度;交费类型;欠费总额;聚合二维码支付订单号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        edNumber = findViewById(R.id.ed_number);
        ivCancelNumber = findViewById(R.id.cancel_number);
        tvMoney = findViewById(R.id.tv_search_money);
        tvAddress = findViewById(R.id.tv_search_address);
        tvName = findViewById(R.id.tv_search_name);
        tvInfo = findViewById(R.id.tv_search_info);
        tvType = findViewById(R.id.tv_search_type);
        linCust = findViewById(R.id.lin_customer);
        initData();

        // 显隐
        edNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivCancelNumber.setVisibility(View.VISIBLE);
                } else {
                    ivCancelNumber.setVisibility(View.INVISIBLE);
                }
            }
        });

        // 全部删除
        ivCancelNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edNumber.setText("");
            }
        });

    }

    private void initData() {
        findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.cancel_number).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                strMoney = "";
                edNumber.setText("");
                if (linCust.getVisibility() == View.VISIBLE) {
                    linCust.setVisibility(View.INVISIBLE);
                }
            }
        });
        findViewById(R.id.bt_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(SpUtil.getShopSearUrl())){
                    ToastManager.getInstance(SearchActivity.this).showToast("您没有绑定商户，请先绑定,然后重新登录");
                    return;
                }
                if (TextUtils.isEmpty(edNumber.getText())) {
                    ToastManager.getInstance(SearchActivity.this).showToast("请输入用户编号");
                    return;
                }
                if (TextUtils.isEmpty(strMoney)) {
                    ToastManager.getInstance(SearchActivity.this).showToast("金额不能为空");
                    return;
                }
                mDialog = new WaitDialog(SearchActivity.this);
                mDialog.show();
                getData();


            }
        });
    }

    private void getData() {
        String url = SpUtil.getShopSearUrl() + edNumber.getText().toString();
        Log.e("getFeesToPay", "url=" + url);
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    // 使用ConcurrentMap存储cookie信息，因为数据在内存中，所以只在程序运行阶段有效，程序结束后即清空
                    private ConcurrentMap<String, List<Cookie>> storage = new ConcurrentHashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        String host = url.host();
                        if (cookies != null && !cookies.isEmpty()) {
                            storage.put(host, cookies);
                        }

                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        String host = url.host();
                        List<Cookie> list = storage.get(host);
                        return list == null ? new ArrayList<Cookie>() : list;
                    }
                })
                .authenticator(new Authenticator() {
                    @Override
                    public okhttp3.Request authenticate(Route route, Response response) throws IOException {
                        return response.request().newBuilder().header("Authorization", "Basic YWRtaW46cGFzc3dvcmQ=").build();
                    }
                })
                .build();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mDialog.dismiss();
                Log.e("getFeesToPay", "失败=" + e.toString());
                SearchActivity.this.runOnUiThread(new TimerTask() {
                    @Override
                    public void run() {
                        ToastManager.getInstance(SearchActivity.this).showToast("网络异常");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mDialog.dismiss();
                String responseStr = response.body().string();
                Log.e("getFeesToPay", "成功=" + responseStr);
                if (responseStr == null || responseStr.length() == 0) {

                    return;
                }
                final CustomerBean bean = new Gson().fromJson(responseStr, CustomerBean.class);
                if (bean.getCode() == 93 && SearchActivity.this != null) {
                    SearchActivity.this.runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            ToastManager.getInstance(SearchActivity.this).showToast("查无此户，重新搜索");
                        }
                    });
                }
                if (bean.getCode() != 0 && SearchActivity.this != null) {
                    SearchActivity.this.runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            ToastManager.getInstance(SearchActivity.this).showToast("搜索失败，检查用户编号，重新搜索");
                        }
                    });
                    return;
                }
                if (!SpUtil.getGSDM().equals(bean.getData().getCompanyCode())){
                    SearchActivity.this.runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            Log.e("GSDM", "不一样GSDM(=" + SpUtil.getGSDM()+" CompanyCode="+bean.getData().getCompanyCode());
                            ToastManager.getInstance(SearchActivity.this).showToast("非法卡号");
                        }
                    });
                    return;
                }
                SearchActivity.this.runOnUiThread(new TimerTask() {
                    @Override
                    public void run() {
                        tvMoney.setText(bean.getData().getTotalfee());
                        tvAddress.setText(bean.getData().getAddress());
                        tvName.setText(bean.getData().getUsername());
                        tvType.setText(bean.getData().getFeetype());
                        tvInfo.setText(bean.getMsg());
                        strMoney = bean.getData().getTotalfee();
                        strNumber = edNumber.getText().toString();
                        strType = bean.getData().getFeetype();
                        strYear = bean.getData().getFeeduration();
                        strName = bean.getData().getUsername();
                        strAddress = bean.getData().getAddress();
                        setMoney();
                        linCust.setVisibility(View.VISIBLE);
                    }
                });
            }
        });
    }

    boolean isTooth = false;

    private void setMoney() {
        findViewById(R.id.bt_no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("daying","SpUtil="+SpUtil.getDaYin());
                if (SpUtil.getDaYin()){
                    if (!ToothMethod.checkBluetoothState(SearchActivity.this)) {
                        if (isTooth) {
                            getQrCode(strMoney);
                        } else {
                            ToastManager.getInstance(SearchActivity.this).showToast("请开启蓝牙,启动打印功能");
                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                            isTooth=true;
                        }
                    } else {
                        getQrCode(strMoney);
                    }
                }else {
                    getQrCode(strMoney);
                }
            }
        });
    }
    int i=0;
    private void getQrCode(final String money) {
        if (Double.parseDouble(money) <= 0) {
            ToastManager.getInstance(SearchActivity.this).showToast("该用户不欠费");
            return;
        }
        // 用户编号;年度;交费类型;欠费总额;聚合二维码支付订单号
        HttpMethod.getQrCode2(SearchActivity.this, money,edNumber.getText().toString(), new StringCallback() {
            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {
                mDialog.dismiss();
            }

            @Override
            public void onResponse(String response) {
                i=i+1;
                QrCodeBean bean = new Gson().fromJson(response, QrCodeBean.class);
                mDialog.dismiss();
                if (bean.getQrBase64()==null&&i>=3){
                    ToastManager.getInstance(SearchActivity.this).showToast("该商户未绑定银行，无法获取二维码");
                    return;
                }
                Intent intent = new Intent(SearchActivity.this, MoneyCodeActivity.class);
                intent.putExtra("qrBase64", bean.getQrBase64());
                intent.putExtra("orderId", bean.getOrderNo());
                intent.putExtra("money", money);
                intent.putExtra("born", "search");
                intent.putExtra("number", strNumber);
                intent.putExtra("year", strYear);
                intent.putExtra("type", strType);
                intent.putExtra("name", strName);
                intent.putExtra("address", strAddress);
                startActivity(intent);
                finish();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
